import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  //登录页面
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login/Login.vue')
  },
  //主页面
  {
    path: '/home',
    name: 'Home',
    //redirect为重定向，重定向到它的子路由/welcome
    redirect: '/welcome',
    children: [
      //主页面的欢迎页面
      {
        path: '/welcome',
        name: 'Welcome',
        component: () => import('@/components/Welcome.vue')
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('../views/user/Users.vue')
      }
    ],
    component: () => import('../views/Home/Home.vue')
  }
]
const router = new VueRouter({
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //如果是访问登录页直接放行
  if (to.path == '/') return next()
  //如果访问其他页面没有token存在就跳转到登录页
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/')
  //如果有token存在直接放行
  next()
})

export default router
